package com.atguigu.service;

import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class SecondKillService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public String secondKill(String skuId){
        String script = "local stock = tonumber(redis.call('get',KEYS[1])) if stock > 0 then redis.call('decr',KEYS[1]) return 1 else return 0 end";
        Boolean execute = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList("sec:skuId:" + skuId), "argv1", "argv2");
        return execute?"success":"fail";
    }

   /* public String secondKill(String skuId) {
       // stringRedisTemplate.opsForValue().decrement("sec:skuId:" + skuId);
        String stockStr = stringRedisTemplate.opsForValue().get("sec:skuId:" + skuId);
        if(StringUtils.isEmpty(stockStr)){
            return "库存为初始化";
        }
        int stock = Integer.parseInt(stockStr);
        if(stock <= 0){
            return "库存不足";
        }
        stock--;
        stringRedisTemplate.opsForValue().set("sec:skuId:" + skuId, stock+"");


        return "success";
    }*/
}
